<?PHP
include("functions.php");
include("cnnxn.php");
connect();
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>daleclark.net</title>
<link type="text/css" rel="stylesheet" href="adminstyles.css" />

<script type="text/javascript" language="javascript">
var upfn;
var upln;
function addPlayer(fn,ln) {
	//alert('hello '+fn+' '+ln);
	upfn=fn;
	upln=ln;
	xmlhttp=GetXmlHttpObject();
	
	if (xmlhttp==null) {
	  alert ("Your browser does not support XMLHTTP!");
	  return;
	} 
	
	//tempStr=str;
	var url="addplayerfromcsvc.php";
	url=url+"?fn="+fn+"&ln="+ln;
	//alert(url);
	xmlhttp.onreadystatechange=stateChanged;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function GetXmlHttpObject() {
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject) {
		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

function stateChanged() {
	if (xmlhttp.readyState==4) {
		if (xmlhttp.responseText!="") {
			document.getElementById('addresponse-'+upfn+'-'+upln).innerHTML=xmlhttp.responseText;
			if (xmlhttp.responseText=='error') {
				document.getElementById('addresponse-'+upfn+'-'+upln).style.color="#990000";
			} else {
				document.getElementById('addresponse-'+upfn+'-'+upln).style.color="#006600";
			}
			//setTimeout('clearfield()',1000);
		}
	}
}
</script>

</head>
<body>
<div id="adminwrapper">
<div id="adminlogo"></div>
<?PHP navigation(); ?>
<div id="admincontent">

<?PHP

$error=0;
if (isset($_POST['submit'])) {
	/*foreach ($_FILES['csvfile'] as $key=>$value) {
		print $key.' - '.$value.'<br />';
	}*/
	move_uploaded_file($_FILES['csvfile']['tmp_name'],'csvfiles/'.$_FILES['csvfile']['name']);
	
	$readfilehandle=fopen('csvfiles/'.$_FILES['csvfile']['name'],'r');
	$readfilehandleb=fopen('csvfiles/'.$_FILES['csvfile']['name'],'r');
	
	$tempArray=array();
	$checkArray=array();
	$tournamentArray=array();
	$teamsArray=array();
	$errorArray=array();
	
	$tournamentDate='';
	$gender='';
	$division='';
	$teams='';
	$genteamsize=0;
	$eventID='';
	
	$loadTournament=1;
	
	$toflag=0;
	$teflag=0;
	
	$SQLt='SELECT * FROM Teams ORDER BY TeamID DESC LIMIT 1;';
	$sendt=mysqli_query($db,$SQLt) or die(mysqli_error($db));
	$RSt=mysqli_fetch_object($sendt);
	$newID=$RSt->TeamID+1;
	
	$passFlag=0;
	
	while($checkArray=fgetcsv($readfilehandle)) {
		if ($checkArray[0]!='' && $checkArray[0]!='Date' && $checkArray[0]!='Gender' && $checkArray[0]!='Division' && $checkArray[0]!='Teams' && $checkArray[0]!='Team Size') {
			foreach($checkArray as $ckey=>$cvalue) {
				if (!ctype_digit($cvalue)) {
					$nameArray=explode(" ",trim(rtrim($cvalue)));
					
					$lastname=$nameArray['1'];
					if (isset($nameArray['2'])) {
						$lastname=$lastname.' '.$nameArray['2'];
					}
											
					$SQLchp='SELECT * FROM Players WHERE firstname LIKE "'.$nameArray[0].'" AND lastname LIKE "'.$lastname.'";';
					$sendchp=mysqli_query($db,$SQLchp) or die(mysqli_error($db));
					if (!$RSchp=mysqli_fetch_object($sendchp)) {
						$errorArray[$error][0]=$nameArray[0];
						$errorArray[$error][1]=$lastname;
						$error++;
					}
				}
			}
		}
	}
	
	if ($error>=1) {
		print '<p style="color:#990000;">The following errors were encountered in this file ('.$error.'). Please correct these and try again.<br />The data has NOT BEEN UPDATED.</p>';
		print '<ul>';
		if (isset($errorArray[0])) {
			foreach ($errorArray as $key=>$value) {
				print '<li>';
				foreach ($value as $ekey=>$evalue) {
					print $evalue.' ';
				}
				print ' - Confirm spelling in the file, or <a href="Javascript:addPlayer(\''.$value[0].'\',\''.$value[1].'\');">Click here to add as a new player</a>, and then re-submit the file. <span id="addresponse-'.$value[0].'-'.$value[1].'" style="color:#000000;"></span></li>';
			}
		}
		print '</ul>';
		fclose($readfilehandle);
		
		print '<hr /><form method="post" action="loadcsv.php" enctype="multipart/form-data">
<input type="file" name="csvfile" />
<input type="submit" name="submit" value="submit" />
</form>';
		
	} else {
	// PROCESS THE FILE 
	
	while($tempArray=fgetcsv($readfilehandleb)) {
		if ($tempArray[0]=='') {
				//print 'date: '.$tournamentDate.' gender: '.rtrim($gender,"s").' division: '.$division.' teams: '.$teams.' team size: '.$genteamsize.'<br /><br />';
				$SQLct='SELECT * FROM Tournaments WHERE StartDate="'.$tournamentDate.'";';
				$sendct=mysqli_query($db,$SQLct) or die(mysqli_error($db));
				if (!$RSct=mysqli_fetch_object($sendct)) {
					$SQLtournament='INSERT INTO Tournaments (StartDate,Name,IsUSOpenQualifier) VALUES ("'.$tournamentDate.'","none",0);';
					$sendtounaments=mysqli_query($db,$SQLtournament) or die(mysqli_error($db));
					
					$SQLt='SELECT * FROM Tournaments WHERE StartDate="'.$tournamentDate.'";';
					$sendt=mysqli_query($db,$SQLt) or die(mysqli_error($db));
					$RSct=mysqli_fetch_object($sendt);
				}
				
				$SQLg='SELECT * FROM Gender WHERE Gender LIKE "'.rtrim($gender,"s").'%";';
				$sendg=mysqli_query($db,$SQLg) or die(mysqli_error($db));
				$RSg=mysqli_fetch_object($sendg);
				
				$SQLd='SELECT * FROM Divisions WHERE Division LIKE "'.$division.'%";';
				$sendd=mysqli_query($db,$SQLd) or die(mysqli_error($db));
				$RSd=mysqli_fetch_object($sendd);
				
				$SQLceid='SELECT * FROM Events WHERE TournamentID='.$RSct->TournamentID.' AND StartDate="'.$tournamentDate.'" AND GenderID='.$RSg->GenderID.' AND DivisionID='.$RSd->DivisionID.';';
				$sendceid=mysqli_query($db,$SQLceid) or die(mysqli_error($db));
				if (!$RSceid=mysqli_fetch_object($sendceid)) {
				
					$SQLevent='INSERT INTO Events (TournamentID,StartDate,GenderID,DivisionID,TeamSize,NumberOfTeams) VALUES ('.$RSct->TournamentID.',"'.$tournamentDate.'",'.$RSg->GenderID.','.$RSd->DivisionID.','.$genteamsize.','.$teams.');';
					$sendevents=mysqli_query($db,$SQLevent) or die(mysqli_error($db));
				
				}
				
				$SQLeid='SELECT * FROM Events ORDER BY EventID DESC LIMIT 1;';
				$sendeid=mysqli_query($db,$SQLeid) or die(mysqli_error($db));
				$RSeid=mysqli_fetch_object($sendeid);
				$eventID=$RSeid->EventID;
			
		} else {
			$tempTeam='';
			$teamsize=0;
			switch ($tempArray[0]) {
				case 'Date' : $tournamentDate=trim($tempArray[1]); break;
				case 'Gender' : $gender=trim($tempArray[1]); break;
				case 'Division' : $division=trim($tempArray[1]); break;
				case 'Teams' : $teams=trim($tempArray[1]); break;
				case 'Team Size' : $genteamsize=trim($tempArray[1]); break;
				default : foreach ($tempArray as $key=>$value) { $tempTeam=$tempTeam.$value.','; if (ctype_digit($value)) { 
				
				// Load Teams
							$trimmedTeam=rtrim($tempTeam,",");
							$loadArray=explode(",",$trimmedTeam);
							foreach ($loadArray as $lkey=>$lvalue) {
								
								$nameArray=array();
								if (!ctype_digit($lvalue)) {
									$nameArray=explode(" ",trim(rtrim($lvalue)));
									$lastname=$nameArray['1'];
									if (isset($nameArray['2'])) {
										$lastname=$lastname.' '.$nameArray['2'];
									}									
									
									$SQLgp='SELECT * FROM Players WHERE firstname LIKE "'.$nameArray[0].'" AND lastname LIKE "'.$lastname.'";';
									$sendgp=mysqli_query($db,$SQLgp) or die(mysqli_error($db));
									if ($RSgp=mysqli_fetch_object($sendgp)) {
										$SQLct='SELECT * FROM Teams WHERE TeamID='.$newID.' AND PlayerID='.$RSgp->PlayerID.';';
										$sendct=mysqli_query($db,$SQLct) or die(mysqli_error($db));
										if (!$RSct=mysqli_fetch_object($sendct)) {								
											$SQLlte='INSERT INTO Teams (TeamID,PlayerID) VALUES ('.$newID.','.$RSgp->PlayerID.');';
											$sendlte=mysqli_query($db,$SQLlte) or die(mysqli_error($db));
											//print '<br />';
										}
									} else {
										print '<p>Please check spelling for <strong style="text-transform:uppercase;">'.$nameArray[0].' '.$lastname.'</strong>, or <a href="Players_viewall.php?fn='.$nameArray[0].'&ln='.$lastname.'">Click Here to add this player</a></p>';
										$error=1;
									}
									
								} else {
									$SQLcr='SELECT * FROM Results WHERE EventID='.$eventID.' AND TeamID='.$newID.' AND Result='.$lvalue.';';
									$sendcr=mysqli_query($db,$SQLcr) or die(mysqli_error($db));
									if (!$RScr=mysqli_fetch_object($sendcr)) {
										$SQLlre='INSERT INTO Results (EventID,TeamID,Result) VALUES ('.$eventID.','.$newID.','.$lvalue.');';
										$sendlre=mysqli_query($db,$SQLlre) or die(mysqli_error($db));
									}
									
								}
							}
							$newID++;
							$tempTeam='';
				//
				
				 		}
				}
			}
			$teflag++;
		}
	}
	fclose($readfilehandleb);
	
	}

}

mysqli_close($db);
?>



</div>
</div>
</body>
</html>